import Vue from 'vue'
import Router from 'vue-router'
import Home from '../views/Home.vue'
import store from '../store/index'
Vue.use(Router)

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
    redirect: '/main'
  }, {
    path: '/index',
    name: 'Index',
    component: () => import(/* webpackChunkName: "login" */ '../views/index.vue'),
    children: [
      {
        path: '/main',
        name: 'Main',
        component: () => import(/* webpackChunkName: "login" */ '../components/main.vue')
      }, {
        path: '/details',
        name: 'Details',
        component: () => import(/* webpackChunkName: "login" */ '../components/details.vue')
      }, {
        path: '/allShop',
        name: 'AllShop',
        component: () => import(/* webpackChunkName: "login" */ '../components/allshop.vue')
      }, {
        path: '/error',
        name: 'Error',
        component: () => import(/* webpackChunkName: "login" */ '../components/myError.vue'),

      }, {
        // collect
        path: '/collect',
        name: 'Collect',
        component: () => import(/* webpackChunkName: "login" */ '../components/collect.vue'),
        // beforeEnter: (to, from, next) => {

        //   if(store.state.userName==''){
        //     next(false)
        //   }else{
        //     next()
        //   }

        // }
      },{
        // indent
        path: '/indent',
        name: 'Indent',
        component: () => import(/* webpackChunkName: "login" */ '../components/indent.vue'),
      },
       {
        path: '/cart',
        name: 'Cart',
        component: () => import(/* webpackChunkName: "login" */ '../components/cart.vue'),
    
      },
      {
        path: '/order',
        name: 'Order',
        component: () => import(/* webpackChunkName: "login" */ '../components/order.vue'),
    
      },
    ]


  }, {
    path: '/head',
    name: 'Head',
    component: () => import(/* webpackChunkName: "login" */ '../components/head.vue'),

  },


]

//控制台会报[NavigationDuplicated {_name: "NavigationDuplicated", name: "NavigationDuplicated"}]。其原因在于Vue-router在3.1之后把$router.push()方法改为了Promise。所以假如没有回调函数，错误信息就会交给全局的路由错误处理，因此就会报上述的错误。
//禁止全局路由错误处理打印，这个也是vue-router开发者给出的解决方案：
const originalPush = Router.prototype.push;
Router.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
};

const router = new Router({
  routes
});
router.beforeEach(function (to, from, next) {
  if (/(collect|indent|cart|order)/.test(to.path)) {
    if (!store.state.userName) {
      next(false)
    } else {
      next()
    }
  }else{
    next()
  }


})
export default router

